package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public Long[] findCategoryPath(Long catId){
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catId,paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catId, List<Long> paths) {
        paths.add(catId);
        CategoryEntity byId = this.getById(catId);
        if(!byId.getParentCid().equals(0L)){
            this.findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> entities = this.baseMapper.selectList(null);
        //组装成tree
        List<CategoryEntity> collect = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildMenu(menu.getCatId(), entities));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return menu1.getSort() - menu2.getSort();
                })
                .collect(Collectors.toList());
        return collect;

    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        //todo 查看是否有在其他地方引用
        this.baseMapper.deleteBatchIds(catIds);
    }

    private List<CategoryEntity> getChildMenu(Long catId,List<CategoryEntity> all) {
        return all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(catId))
                .map(menu->{
                    menu.setChildren(getChildMenu(menu.getCatId(),all));
                    return menu;
                        }
                ).sorted((menu1,menu2)->{return menu1.getSort()-menu2.getSort();})
                .collect(Collectors.toList());
    }

}
